/*
 * 
 */
package com.ap.core.business.message.response.translators.header.impl;

import com.ap.core.business.message.response.translators.ResponseTranslator;
import com.ap.core.business.message.response.translators.listener.ResponseListener;
import com.ap.core.common.types.InputMessageType;
import com.ap.core.common.types.SystemTypeCode;
import com.ap.core.cxf.jaxb.msghdr.MsgHdrType;
import com.ap.core.domain.sequence.generation.MultiIdGenerationService;
import com.ap.core.exception.BusinessFailureException;
import com.ap.core.message.info.PaymentResponseMessageInfo;
import com.ap.core.message.info.RequestMessageInfo;
import org.joda.time.DateTime;
import org.joda.time.LocalDateTime;

import java.text.SimpleDateFormat;

/**
 * User: Ranjit.Singh
 * implementation class for {@link ResponseTranslator} to populate {@link MsgHdrType}  in response object
 */
public abstract class AbstractMsgHdrResponseTranslator<T> implements ResponseTranslator<RequestMessageInfo<T> , PaymentResponseMessageInfo>{

    protected MultiIdGenerationService<Long> multiIdGenerationService;


    public void setMultiIdGenerationService(MultiIdGenerationService<Long> multiIdGenerationService) {
        this.multiIdGenerationService = multiIdGenerationService;
    }
    
    protected void buildMsgHdrType(String requestMsgId,
								   PaymentResponseMessageInfo response,
			                       ResponseListener responseListener,
			                       final InputMessageType inputMessageType)
			                        throws BusinessFailureException {
		final MsgHdrType msgHdrType = new MsgHdrType();
        msgHdrType.setMsgTimestamp(new LocalDateTime());
        msgHdrType.setMsgId(getMessageIdentifier());
        msgHdrType.setMsgType(inputMessageType.getOutputMsgTypeEnum());
        msgHdrType.setOrgReqMsgId(requestMsgId);
        response.setMsgHdr(msgHdrType);

        responseListener.onMessageHeaderResponse(response);
	}

    private String getMessageIdentifier(){
        //Generate it AP[DDMMYYYY][TIME OF DAY IN MILI SECS][ORACLESEQ]
        final SimpleDateFormat FORMAT = new SimpleDateFormat("ddMMyyyy");
        StringBuilder builder = new StringBuilder(SystemTypeCode.AP.name());

        final DateTime dateTime = new DateTime();
        String date = FORMAT.format(dateTime.toDate());
        builder.append(date);
        builder.append(dateTime.getMillisOfDay());
        builder.append(multiIdGenerationService.getNextId("OUTPUT_MSG_ID"));
        String msgId =  builder.toString();
        return msgId.length() > 35 ? msgId.substring(0,35) : msgId;
    }


}
